from sqlalchemy import Column, Integer, String, Text, DateTime, Float, JSON, BigInteger, SmallInteger, ForeignKey, Boolean
import datetime

from db import Base


class Article(Base):
    __tablename__ = 'articles'
    id = Column(BigInteger, primary_key=True, autoincrement=True)
    title = Column(String(512), nullable=False)
    url = Column(String(512), nullable=False, unique=True)
    content = Column(Text)
    summary = Column(String(256))
    publish_time = Column(DateTime)
    source = Column(String(128))
    crawl_status = Column(SmallInteger, default=0)  # 0未采集/1已采集
    attachments = Column(JSON)
    minio_urls = Column(JSON)
    is_enterprise_related = Column(Boolean, default=False)  # 是否与企业相关
    relevance_score = Column(Float, default=0.0)  # 相关性评分(0-100)
    created_at = Column(DateTime, default=datetime.datetime.utcnow)

class CrawlTask(Base):
    __tablename__ = 'crawl_task'
    id = Column(BigInteger, primary_key=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    source = Column(String(128))
    status = Column(SmallInteger, default=0)  # 0进行中/1完成
    progress = Column(Float, default=0.0)
    total_count = Column(Integer, default=0)
    finished_count = Column(Integer, default=0)
    params = Column(JSON)
    created_at = Column(DateTime, default=datetime.datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow)


class DataSource(Base):
    """数据源配置表"""
    __tablename__ = 'data_sources'
    id = Column(BigInteger, primary_key=True, autoincrement=True)
    source_id = Column(String(128), unique=True, nullable=False)  # 数据源唯一标识
    name = Column(String(256), nullable=False)  # 数据源名称
    description = Column(Text)  # 数据源描述
    base_url = Column(String(512), nullable=False)  # 基础URL
    category = Column(String(64), nullable=False)  # 标签：法规、文件、标准、安全科普、事故案例
    is_active = Column(Boolean, default=True)  # 是否启用
    spider_config = Column(JSON)  # 爬虫配置参数
    created_at = Column(DateTime, default=datetime.datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow)


class GlobalConfig(Base):
    """全局配置表"""
    __tablename__ = 'global_config'
    id = Column(BigInteger, primary_key=True, autoincrement=True)
    config_key = Column(String(128), unique=True, nullable=False)  # 配置键
    config_value = Column(JSON)  # 配置值
    description = Column(String(512))  # 配置描述
    created_at = Column(DateTime, default=datetime.datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow)
